import * as echarts from 'echarts'
import { getUserDetail, getUserAiAnaly, getUserOrganization } from '@/api/user'

export default {
  data() {
    return {
      loading: false,
      aiLoading: false,
      orgLoading: false,
      user: {
        userVo: {},
        profile: {},
        userDetailReport: {}
      },
      organizationChain: [],
      currentOrganization: null,
      genderMap: { M: '男', F: '女' },
      statusMap: { '0': '禁用', '1': '启用' },
      emotionChartInstance: null,
      interestChartInstance: null
    }
  },
  mounted() {
    this.fetchDetail()
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
    if (this.emotionChartInstance) this.emotionChartInstance.dispose()
    if (this.interestChartInstance) this.interestChartInstance.dispose()
  },
  methods: {
    async fetchDetail() {
      const user_uid = this.$route.query.user_uid
      if (!user_uid) {
        this.$message.error('缺少用户参数 user_uid')
        return
      }
      this.loading = true
      try {
        // 先请求基础详情，尽快渲染
        const detailRes = await getUserDetail({ user_uid })
        const baseData = (detailRes && detailRes.data) || {}
        this.user = Object.assign({ userVo: {}, profile: {}, userDetailReport: {}}, baseData)
        this.$nextTick(() => {
          this.renderEmotionChart()
          this.renderInterestChart()
        })
        // 基础信息就绪后立刻加载机构信息
        this.fetchOrganizationChain()
      } catch (e) {
        // 已统一处理
      } finally {
        this.loading = false
      }

      // 再异步请求 AI 分析，不阻塞首屏
      this.aiLoading = true
      try {
        const aiRes = await getUserAiAnaly({ user_uid })
        const aiData = (aiRes && aiRes.data) || {}
        this.$set(this.user, 'userDetailReport', aiData)
      } catch (e) {
        // 忽略AI报告错误，保证基础信息可用
      } finally {
        this.aiLoading = false
      }

      // 机构信息已在基础详情后立即触发加载
    },
    async fetchOrganizationChain() {
      this.orgLoading = true
      // 从用户详情数据中获取 org_id
      const orgId = (this.user && this.user.userVo && (this.user.userVo.org_id || this.user.userVo.orgId)) || (this.user && this.user.profile && (this.user.profile.org_id || this.user.profile.orgId))
      if (!orgId) {
        this.organizationChain = []
        this.currentOrganization = null
        this.orgLoading = false
        return
      }
      try {
        const chain = []
        // 第一次：根据 org_id 查询当前机构
        const res = await getUserOrganization({ org_id: orgId })
        let node = (res && res.data) || null
        while (node) {
          chain.push(node)
          const parentId = node.parentId || node.parent_id
          if (parentId === null || parentId === undefined || parentId === '') break
          const parentRes = await getUserOrganization({ org_id: parentId })
          node = (parentRes && parentRes.data) || null
        }
        // 面包屑按 根 -> 叶 展示
        this.organizationChain = chain.slice().reverse()
        // 当前机构为叶子（用户直接所在的机构）
        this.currentOrganization = chain[0] || null
      } catch (e) {
        // 忽略机构错误
        this.organizationChain = []
        this.currentOrganization = null
      } finally {
        this.orgLoading = false
      }
    },
    displayVal(val) {
      if (val === null || val === undefined || val === '') return '无'
      return String(val)
    },
    getStatusDisplay(status) {
      if (status === null || status === undefined || status === '') return '无'
      const map = { '0': '禁用(0)', '1': '正常(1)', '2': '封禁(2)', '3': '已排除(3)' }
      return map[String(status)] || `未知(${status})`
    },
    getGenderDisplay(gender) {
      if (!gender) return '未知(U)'
      const map = { M: '男(M)', F: '女(F)' }
      return map[gender] || '未知(U)'
    },
    formatDate(val) {
      if (!val) return '-'
      // 兼容 ISO 字符串或时间戳
      const date = typeof val === 'string' || typeof val === 'number' ? new Date(val) : val
      if (isNaN(date.getTime())) return val
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const d = String(date.getDate()).padStart(2, '0')
      const hh = String(date.getHours()).padStart(2, '0')
      const mm = String(date.getMinutes()).padStart(2, '0')
      const ss = String(date.getSeconds()).padStart(2, '0')
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
    },
    parseJSONSafely(str, fallback) {
      try {
        if (!str) return fallback
        return JSON.parse(str)
      } catch (e) {
        return fallback
      }
    },
    renderEmotionChart() {
      const emotionRaw = (this.user.profile && this.user.profile.emotionVector) || null
      const emotion = this.parseJSONSafely(emotionRaw, {})
      const indicators = Object.keys(emotion).map(k => ({ name: k, max: 1 }))
      const values = Object.values(emotion)

      if (!this.emotionChartInstance) {
        this.emotionChartInstance = echarts.init(this.$refs.emotionChart)
      }
      const option = {
        tooltip: {},
        radar: {
          indicator: indicators,
          radius: '65%'
        },
        series: [{
          type: 'radar',
          data: [
            { value: values, name: '情绪' }
          ]
        }]
      }
      this.emotionChartInstance.setOption(option)
    },
    renderInterestChart() {
      const interestRaw = (this.user.profile && this.user.profile.interestMatrix) || null
      const interest = this.parseJSONSafely(interestRaw, {})
      const entries = Object.entries(interest)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 10)
      const labels = entries.map(e => e[0])
      const values = entries.map(e => Number(e[1]))

      if (!this.interestChartInstance) {
        this.interestChartInstance = echarts.init(this.$refs.interestChart)
      }
      const option = {
        tooltip: { trigger: 'axis' },
        grid: { left: 80, right: 20, top: 20, bottom: 20 },
        xAxis: { type: 'value' },
        yAxis: { type: 'category', data: labels, inverse: true },
        series: [{
          type: 'bar',
          data: values,
          itemStyle: { color: '#409EFF' }
        }]
      }
      this.interestChartInstance.setOption(option)
    },
    resizeCharts() {
      if (this.emotionChartInstance) this.emotionChartInstance.resize()
      if (this.interestChartInstance) this.interestChartInstance.resize()
    },
    // AI分析报告相关方法
    getEmotionStatusText(status) {
      const statusMap = {
        1: '积极情绪',
        2: '中性情绪',
        3: '消极情绪',
        4: '极端情绪'
      }
      return statusMap[status] || '未知状态'
    },
    getEmotionStatusClass(status) {
      const classMap = {
        1: 'emotion-positive', // 积极情绪 - 绿色
        2: 'emotion-neutral', // 中性情绪 - 蓝色
        3: 'emotion-negative', // 消极情绪 - 橙色
        4: 'emotion-extreme' // 极端情绪 - 红色
      }
      return classMap[status] || 'emotion-unknown'
    }
  }
}
